package droid.frame.view;

import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ScrollView;

/**
 * 解决SwipeRefreshLayout(嵌套ScrollView)嵌套ViewPager的问题<br>
 * 用法 {@link ViewPagerExt#setOnTouchListener(SwipeScrollViewViewPagerListener)} <br>
 * 如果仅仅是SwipeRefreshLayout嵌套ViewPager,则调用 {@link SwipeViewPagerOnTouchllListener}
 * 
 * @author coffee<br>
 *         2017-1-9下午3:34:07
 */
public class SwipeScrollViewViewPagerListener implements OnTouchListener {

	private SwipeRefreshLayout mSwipeLayout;
	private ScrollView mScrollView;
	private SwipeScrollViewOnScrollChangedListener scrollChangedListener;

	/**
	 * 
	 * @param swipeRefreshLayout
	 * @param scrollView
	 *            如果是SwipeRefreshLayout直接嵌套ViewPager,则scrollView传入null
	 */
	public SwipeScrollViewViewPagerListener(SwipeRefreshLayout swipeRefreshLayout, ScrollView scrollView) {
		mSwipeLayout = swipeRefreshLayout;
		mScrollView = scrollView;
		if (mScrollView != null) {
			scrollChangedListener = new SwipeScrollViewOnScrollChangedListener(mSwipeLayout, mScrollView);
			mScrollView.getViewTreeObserver().addOnScrollChangedListener(scrollChangedListener);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:// 经测试，ViewPager的DOWN事件不会被分发下来
		case MotionEvent.ACTION_MOVE:
			if (mScrollView != null) {
				mScrollView.getViewTreeObserver().removeOnScrollChangedListener(scrollChangedListener);
			}
			mSwipeLayout.setEnabled(false);
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			mSwipeLayout.setEnabled(true);
			if (mScrollView != null) {
				mScrollView.getViewTreeObserver().addOnScrollChangedListener(scrollChangedListener);
			}
			break;
		}
		return false;
	}
}
